package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCode")
public class ValidateController {

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/send4Order")
    public Result send4Order(String telephone) {


        try {
            //生成随机验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);

            //向用户发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code + "");

            //发送成功后需要将验证码存到redis中 设置过期时间,用于预约时的比对
            jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_ORDER, 300, code + "");

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }


        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    @RequestMapping("/send4Login")
    public Result send4Login(String telephone) {


        try {
            //生成随机6位验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);

            //向用户发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code + "");

            //发送成功后需要将验证码存到redis中 设置过期时间,用于预约时的比对
            jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_LOGIN, 300, code + "");

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }


        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
